package com.avic.modules.realtime.client;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.avic.modules.realtime.constants.RedisKeyConstant;
import com.avic.modules.realtime.constants.RedisOPCItem;
import com.avic.modules.realtime.entity.OpcWsIPA;
import com.avic.utils.RedisUtils;
import com.avic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

/**
 * @author ayetony.miao
 * @date 2022/8/18 10:44
 **/
@Slf4j
public class WebSocketClientCollector extends WebSocketClient {


    private boolean CONN_ST = false;

    public boolean isCONN_ST() {
        return CONN_ST;
    }

    public void setCONN_ST(boolean CONN_ST) {
        this.CONN_ST = CONN_ST;
    }
    private final RedisUtils redisUtils;

    public WebSocketClientCollector(URI serverUri, RedisUtils redisUtils) {
        super(serverUri);
        this.redisUtils = redisUtils;
    }


    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        CONN_ST = true;
        log.info("[WebSocket collector 】采集连接中,{}", serverHandshake.getHttpStatusMessage());
    }

    @Override
    public void onMessage(String message) {
        if (CONN_ST && !StringUtils.isEmpty(message)) {
            try {
                JSONObject jsonObject = JSONUtil.parseObj(message);
                String tag = (String) jsonObject.get("tag");
                String value = jsonObject.get("value").toString();
                String isoTimeStr = (String) jsonObject.get("sourceTime");
                redisUtils.hset(tag, RedisOPCItem.TIME_STAMP_ITEM, OpcWsIPA.getTime(isoTimeStr));
                redisUtils.hset(tag, RedisOPCItem.ITEM_VALUE, value);
                log.debug("[ Java websocket socket collecting , tag:{} value：{} ]",tag,value);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("[ collect ws opc data error,exception msg：{} ]", e.getMessage());
            }
        }
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        CONN_ST = false;
    }

    @Override
    public void onError(Exception e) {
        CONN_ST = false;
    }

}
